package com.handler.manager;


import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com.message.BasePacket;

public abstract class PacketHandlerManager<T extends BasePacket> {
    protected final Map<Short, PacketHandler<T>> handlers = new ConcurrentHashMap<Short, PacketHandler<T>>();

    /**
     * 注册一个网络包处理类(可以重新注册handler)
     *
     * @param handler 待注册的处理器
     */
    public void registerHandler(PacketHandler<T> handler) {
        if (handlers.containsKey(handler.getCmd()))
            System.out.println("re-register handler["+handler.getCmd()+"]");
        handlers.put(handler.getCmd(), handler);
    }

    public abstract PacketHandler<T> getHandler(T packet);

    /**
     * 将网络包分发给各个handler
     *
     * @param packet 网络包
     */
    public void forward(T packet) throws Exception {
        PacketHandler<T> handler = getHandler(packet);
        if (handler == null) {
            System.out.println("handler not registered!" + packet.toString());
            return;
        }
        handler.handle(packet);
    }
}
